package com.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blog.entity.Comment;
import com.blog.entity.User;
import com.blog.mapper.CommentMapper;
import com.blog.service.CommentService;
import com.blog.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    private final CommentMapper commentMapper;

    public CommentServiceImpl(CommentMapper commentMapper) {
        this.commentMapper = commentMapper;
    }

    @Override
    @Transactional
    public Comment createComment(Comment comment) {
        commentMapper.insert(comment);
        return comment;
    }

    @Override
    @Transactional
    public Comment updateComment(Comment comment) {
        commentMapper.updateById(comment);
        return comment;
    }

    @Override
    @Transactional
    public void deleteComment(Long id) {
        commentMapper.deleteById(id);
    }

    @Override
    public Comment findById(Long id) {
        return commentMapper.selectById(id);
    }

    @Override
    public List<Comment> findByArticleId(Long articleId) {
        return commentMapper.findCommentsWithUserByArticleId(articleId);
    }

    @Override
    public IPage<Comment> findByArticleId(Long articleId, Page<Comment> page) {
        IPage<Comment> commentsPage = commentMapper.findCommentsWithUserByArticleIdPage(page, articleId);
        // 手动获取评论总数
        Long total = commentMapper.countCommentsByArticleId(articleId);
        // 将总数设置到分页结果中
        commentsPage.setTotal(total);
        return commentsPage;
    }

    @Override
    public List<Comment> findByUserId(Long userId) {
        return commentMapper.selectList(new QueryWrapper<Comment>()
            .eq("user_id", userId)
            .orderByDesc("create_time"));
    }

    @Override
    public IPage<Comment> findByUserId(Long userId, Page<Comment> page) {
        return commentMapper.selectPage(page, new QueryWrapper<Comment>()
            .eq("user_id", userId)
            .orderByDesc("create_time"));
    }

    @Override
    public long getCommentCount() {
        return commentMapper.selectCount(null);
    }
} 